package com.c.yinyuezhushou.Service;

import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.task.DownloadTask;
import com.arialyy.aria.util.ALog;
import com.c.yinyuezhushou.MRetrofit.MusicItem;
import com.c.yinyuezhushou.MRetrofit.MyObserver;
import com.c.yinyuezhushou.MRetrofit.MyRetrofit;
import com.c.yinyuezhushou.MRetrofit.RetrofitService;
import com.c.yinyuezhushou.MRetrofit.getSongUrl;
import com.c.yinyuezhushou.MyApplication;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class DownService extends Service {
    private List<OnStateChangeListenr> onStateChangeListenrs = new ArrayList<>();
    private MyApplication myApplication;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new DownServiceIBinder();
    }

    public class DownServiceIBinder extends Binder {
        public DownService getDownService(){
            return DownService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Aria.download(DownService.this).register();
        Aria.download(this).resumeAllTask();
        myApplication = (MyApplication) getApplicationContext();
    }
    @Override public void onDestroy() {
        super.onDestroy();
        Aria.download(this).unRegister();
    }

    public List<DownloadEntity> getNoDownloadEntity(){
        List<DownloadEntity> list = Aria.download(this).getAllNotCompleteTask();
        if (list==null){
            list = new ArrayList<DownloadEntity>();
        }
        return list;
    }

    public List<DownloadEntity> getDownloadEntity(){
        List<DownloadEntity> list = Aria.download(this).getAllCompleteTask();
        if (list==null){
            list = new ArrayList<DownloadEntity>();
        }
        return list;
    }

    public void downloadMusicItem(MusicItem musicItem, int br){
        MyRetrofit.Down(super.getApplicationContext(), RetrofitService.class).getSong(musicItem.getId(),br).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new MyObserver<getSongUrl>() {
            @Override
            public void onNext(@NonNull getSongUrl getSongUrl) {
                try {
                    if (getSongUrl!=null) {
                        if (getSongUrl.getData() != null) {
                            int v = Build.VERSION.SDK_INT;
                            if (v>20&&v<30){
                                String url = getSongUrl.getData().get(0).getUrl();
                                long taskId = Aria.download(this)
                                        .load(url)//读取下载地址
                                        .setFilePath(myApplication.getSetup().getPath()+musicItem.getSong()+" - "+musicItem.getSinger()+"."+StringUtils.split(url,".")[4]) //设置文件保存的完整路径
                                        .create();

                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("id",musicItem.getId());
                                jsonObject.put("song",musicItem.getSong());
                                jsonObject.put("singer",musicItem.getSinger());
                                jsonObject.put("imageurl",musicItem.getImageurl());
                                Aria.download(this).load(taskId).setExtendField(jsonObject.toString()).save();
                            }else {
                                String url = getSongUrl.getData().get(0).getUrl();
                                long taskId = Aria.download(this)
                                        .load(url)//读取下载地址
                                        .setFilePath(getBaseContext().getExternalFilesDir("music").getPath()+"/"+musicItem.getSong()+" - "+musicItem.getSinger()+"."+StringUtils.split(url,".")[4]) //设置文件保存的完整路径
                                        .create();
                                Log.d("test1",getBaseContext().getExternalCacheDir().getPath());
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("id",musicItem.getId());
                                jsonObject.put("song",musicItem.getSong());
                                jsonObject.put("singer",musicItem.getSinger());
                                jsonObject.put("imageurl",musicItem.getImageurl());
                                Aria.download(DownService.this).load(taskId).setExtendField(jsonObject.toString()).save();
                            }
                        }
                    }
                }catch (Exception e){
                    Toast.makeText(myApplication, musicItem.getSong()+" - "+musicItem.getSinger()+"下载失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                Toast.makeText(myApplication, "下载错误", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Download.onTaskStart public void onTaskStart(DownloadTask task) {
        for (OnStateChangeListenr listenr : onStateChangeListenrs){
            listenr.onDown(task);
        }
    }

    @Download.onTaskComplete public void onTaskComplete(DownloadTask task) {
        for (OnStateChangeListenr listenr : onStateChangeListenrs){
            listenr.onCarryout(task);
        }
        int v = Build.VERSION.SDK_INT;
        if (v>30){
            copyPrivateToDownload(this,task.getFilePath(),task.getEntity().getFileName());
        }
    }

    @Download.onTaskRunning public void onTaskRunning(DownloadTask task) {

        for (OnStateChangeListenr listenr : onStateChangeListenrs){
            listenr.onDownschedule(task);
        }
    }


    public interface OnStateChangeListenr {
        void onDown(DownloadTask task);
        void onDownschedule(DownloadTask task);
        void onCarryout(DownloadTask task);
    }

    public void addOnStateChangeListenr(DownService.OnStateChangeListenr l) {
        //将监听器添加到列表
        onStateChangeListenrs.add(l);
    }
    public void removeOnStateChangeListenerInner(DownService.OnStateChangeListenr l) {
        //将监听器从列表中移除
        onStateChangeListenrs.remove(l);
    }

    public static void copyPrivateToDownload(Context context, String orgFilePath, String displayName){
        ContentValues values = new ContentValues();
        //values.put(MediaStore.Images.Media.DESCRIPTION, "This is a file");
        values.put(MediaStore.Audio.Media.DISPLAY_NAME, displayName);
        values.put(MediaStore.Audio.Media.DATE_TAKEN,System.currentTimeMillis());
        values.put(MediaStore.Audio.Media.MIME_TYPE,"audio/x-mpeg");//MediaStore对应类型名
        values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/月光");//公共目录下目录名

        ContentResolver resolver = context.getContentResolver();

        Uri insertUri = resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,values);//使用ContentResolver创建需要操作的文件
        Log.i("test1","insertUri: " + insertUri);


        InputStream ist=null;
        OutputStream ost = null;
        try {
            File file = new File(orgFilePath);
            Log.d("test1",file.length()+"");
            ist=new FileInputStream(file);
            if (insertUri != null) {
                ost = resolver.openOutputStream(insertUri);
            }
            if (ost != null) {
                byte[] buffer = new byte[4096];
                int byteCount = 0;
                while ((byteCount = ist.read(buffer)) != -1) {  // 循环从输入流读取 buffer字节
                    ost.write(buffer, 0, byteCount);        // 将读取的输入流写入到输出流
                }
            }
        } catch (IOException e) {
            //Log.i("copyPrivateToDownload--","fail: " + e.getCause());
        } finally {
            try {
                if (ist != null) {
                    ist.close();
                }
                if (ost != null) {
                    ost.close();
                }
            } catch (IOException e) {
                //Log.i("copyPrivateToDownload--","fail in close: " + e.getCause());
            }
        }
    }


}
